package com.fs.console.base.service;

import cn.hutool.core.util.ReUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.common.baseMapper.*;
import com.fs.common.pojo.*;
import com.fs.common.utils.BaseUtile;
import com.fs.common.utils.ConcurrentHashMapCacheUtils;
import com.fs.common.yzMapper.ProductMapper;
import com.fs.console.base.param.SysConstant;
import com.fs.console.base.utils.ApplicationUtils;
import com.fs.console.base.utils.DateUtils;
import com.fs.console.base.utils.EncodeUtil;
import com.fs.console.base.utils.StringToolUtils;
import com.fs.console.base.vo.LoginUser;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ACE
 * @desc 登录业务类
 * @creationTime 2019-04-03 21:30
 * @projectName weixinframe
 * @packageName com.fs.base.service
 */
@Slf4j
@Service
public class LoginSerevice {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private IntegralMapper integralMapper;
    @Setter
    @Getter
    @Value("${sms.comId}")
    private String comId;

    public LoginUser login(User user){
        LoginUser loginVo = null;
        String account = user.getAccount();
        String pwd = user.getPwd();
        User u = null;
        List<Company> company = null;
        try {
            Pattern pattern = Pattern.compile("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$");
            Matcher matcher = pattern.matcher(account);
            if(matcher.matches()){
                u = userMapper.findByMobileAndPwd(account, pwd);
            }else{
                u = userMapper.findByAccountAndPwd(account, pwd);
            }

        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            loginVo = LoginUser.builder().user(user).loginStatus(false)
                    .loginResult("该账号存在重复，请联系系统管理员!").loginTime(new Date()).build();
            return loginVo;
        }
        if(u!=null){
            if("1".equals(u.getUserStatus())){
                loginVo = LoginUser.builder().user(user).loginStatus(false)
                        .loginResult("该账号已被禁用，请联系系统管理员!").loginTime(new Date()).build();
                return loginVo;
            }
            QueryWrapper<Company> companyQueryWrapper = new QueryWrapper<>();
            companyQueryWrapper.eq("company_status","0");
            if(!u.isSysAdm()){
                companyQueryWrapper.like("line",u.getComId());
            }
            company = companyMapper.selectList(companyQueryWrapper);
            if(CollectionUtils.isEmpty(company)){
                loginVo = LoginUser.builder().user(user).loginStatus(false)
                        .loginResult("该账号未绑定部门或部门已被禁用，请联系系统管理员").loginTime(new Date()).build();
                return loginVo;
            }
            Boolean sysAdm = u.isSysAdm();
            loginVo = LoginUser.builder().user(u).loginStatus(true)
                    .loginResult("登录成功!").loginTime(new Date()).build();
            loginVo.setCompany(companyMapper.selectById(u.getComId()));
            loginVo.setCompanyList(company);
        }else{
            loginVo = LoginUser.builder().user(user).loginStatus(false)
                    .loginResult("手机号或密码错误!").loginTime(new Date()).build();
        }
        return loginVo;
    }

    /**
     * 用户注册
     * userType 用户类型  0.月子会所用户(需要检查企业名称或者识别码)  1.个人用户  必填
     * companyName 企业名称或者识别码                                       userType为0时必填
     * name 用户昵称                                                       必填
     * mobile 用户手机号码                                                  必填
     * verificationCode 验证码                                             必填
     * decoder 推荐码                                                      选填
     * @return User 里面只包含手机号码和没有经过加密的密码
     */
    public User register(Map map)throws Exception{
        String userType = StringToolUtils.SystemGetString("userType");
        String companyName = StringToolUtils.SystemGetString("companyName");
        String name = StringToolUtils.SystemGetString("name");
        String mobile = StringToolUtils.SystemGetString("mobile");
        String verificationCode = StringToolUtils.SystemGetString("verificationCode");
        String decoder = StringToolUtils.SystemGetString("decoder");
        /*String pwd = StringToolUtils.SystemGetString("pwd");*/
        if(StringUtils.isBlank(userType)){
            throw new Exception("必填项不能为空");
        }
        if(StringUtils.isBlank(name) || StringUtils.isBlank(mobile) || StringUtils.isBlank(verificationCode)){
            throw new Exception("必填项不能为空");
        }
        Object cache = ConcurrentHashMapCacheUtils.getCache(mobile);
        if(cache == null){
            throw new Exception("验证码已失效，请重新发送。");
        }
        List<String> strings = ApplicationUtils.decryptToken(cache.toString());
        Date date = DateUtils.parseDate(strings.get(1), SysConstant.DATA_DORMAT);
        Long times = new Date().getTime() - date.getTime();
        if(times > 1000 * 60 * 5){//5分钟
            ConcurrentHashMapCacheUtils.deleteCache(mobile);
            throw new Exception("验证码已失效，请重新发送。");
        }
        if(!verificationCode.equals(strings.get(0))){
            throw new Exception("验证码错误，请填写正确的验证码。");
        }
        String comIds = "";
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        if(userType.equals("0")){
            roleQueryWrapper.eq("role_code", Role.YUE_ZI_ROLES);
            if(StringUtils.isBlank(companyName)){
                throw new Exception("必填项不能为空");
            }
            boolean isMatch = ReUtil.isMatch("^[1-9]\\d*$", companyName);
            if(isMatch){
                Company company = companyMapper.findOneByKeyCode(companyName);
                if(null == company){
                    throw new Exception("月子会所识别码错误");
                }
                comIds = company.getId();
            }else{
                Company company = new Company(companyName);
                companyMapper.insert(company);
                comIds = company.getId();
            }
        }else{
            roleQueryWrapper.eq("role_code", Role.ORDINARY_ROLES);
            comIds = comId;
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        User users = userMapper.selectOne(wrapper);
        if(users != null){
            throw new Exception("帐号已存在，请填写正确的手机号码。");
        }
        String password = BaseUtile.generatePassword(6);
        User user = new User(mobile, EncodeUtil.getSignAndMD5(password),name,mobile,comIds);
        QueryWrapper<Product> queryWrapper = new QueryWrapper();
        queryWrapper.eq("type","basic");
        Product product = productMapper.selectOne(queryWrapper);
        user.setProductId(product.getId());
        user.setIsUpdatePwd(1);
        if(StringUtils.isNoneBlank(decoder)){
            User user1 = userMapper.findOneByDecoder(decoder);
            if(null == user1){
                throw new Exception("推荐码错误");
            }
            user.setOtherDecoder(decoder);
            Integral integral = new Integral();
            integral.setIntegral(50);
            integral.setType(1);
            integral.setUserId(user1.getId());
            integral.setRemark("被推荐人昵称："+user.getNickName()+"，手机号码："+user.getMobile());
            integralMapper.insert(integral);
            user1.setIntegral(user.getIntegral()+50);
            userMapper.updateById(user1);
        }
        userMapper.insert(user);
        List<Role> roles = roleMapper.selectList(roleQueryWrapper);
        if(!CollectionUtils.isEmpty(roles)){
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(roles.get(0).getId());
            userRoleMapper.insert(userRole);
        }
        return new User(mobile,password);
    }
}
